Native Application Development with Android - Topic 4 Summary

1. Getting Started with Android Development

Android is the world's most popular mobile operating system, powering over 80% of smartphones and various other devices.

1.1 What is Android?

Key Challenges in Android Development:

1.2 Setting Up Development Environment

Android Studio

Official IDE for Android development with features:

Project Structure

Folder Purpose
manifests/ AndroidManifest.xml - app description and permissions
java/ Java/Kotlin source code packages
res/ Resources (XML): layouts, strings, images, colors, dimensions
build.gradle Gradle build configuration files

Gradle Build System

Modern build system that handles:

Three build.gradle files:

Running Your App

  1. Connect physical device with USB debugging enabled
  2. Set up Android Virtual Device (AVD) in Android Studio
  3. Click "Run" button to deploy and test
  4. Use Logcat for debugging and monitoring app behavior

Logging in Android

Use Logcat to view system and app logs:

2. Working with User Interfaces

2.1 App Manifest and Resources

AndroidManifest.xml - Essential File:

Describes app components, permissions, and requirements to the Android system.

Key Manifest Elements

Element Purpose Example
Activity Declares an Activity component <activity android:name=".MainActivity">
Service Declares a Service component <service android:name=".MyService">
BroadcastReceiver Declares a BroadcastReceiver component <receiver android:name=".MyReceiver">
ContentProvider Declares a ContentProvider component <provider android:name=".MyProvider">
uses-permission Requests system permissions <uses-permission android:name="android.permission.INTERNET"/>
uses-feature Specifies required hardware features <uses-feature android:name="android.hardware.camera"/>
intent-filter Defines how components can be started
<intent-filter>
  <action android:name="android.intent.action.MAIN"/>
  <category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>

Alternative Resources

Create configuration-specific resource folders:

2.2 Activities and Fragments

Activity: A single focused thing a user can do. Manages a window for UI placement.
Fragment: Reusable portion of UI that can be combined in different ways in Activities.

Creating an Activity

  1. Define layout in XML (res/layout/activity_main.xml)
  2. Create Activity class extending AppCompatActivity
  3. Connect Activity with Layout using setContentView()
  4. Declare Activity in AndroidManifest.xml

Sample Activity Code

// 1. Define layout in XML (activity_main.xml) <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/show_count" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello Android!" /> </RelativeLayout> // 2. Create Activity class public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 3. Set content view setContentView(R.layout.activity_main); } } // 4. Declare in AndroidManifest.xml <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>

Activity Lifecycle

Active/Running
Visible
Stopped/Hidden
Destroyed


Lifecycle Callbacks:
onCreate() → onStart() → onResume() → (active)

onPause() → onStop() → onDestroy()

Activity States

State Description System Behavior
Active/Running Foreground activity, user interaction All components active
Visible Partially obscured, still visible Retains state, active
Stopped/Hidden Completely obscured by another activity Retains state, may be killed
Destroyed Process terminated All resources released

Three Key Loops

2.3 Layouts, Adapters, Action Bar, Dialogs and Notifications

Views and View Groups

Category Examples Purpose
View Button, TextView, EditText, ImageView Basic UI building blocks
ViewGroup ConstraintLayout, LinearLayout, RelativeLayout, FrameLayout Containers that hold and arrange Views
Adapter RecyclerView.Adapter, ArrayAdapter Bridges between data and Views

Common Layout Classes

Layout Description Use Case
ConstraintLayout Connects views with constraints to edges and other views Complex UIs with flexible positioning
LinearLayout Organizes views in horizontal or vertical row Simple lists or forms
RelativeLayout Positions views relative to each other Traditional Android layouts
GridLayout Organizes views in grid structure Tabular data display
FrameLayout Displays single child or stack of children Fragments, simple overlays
ScrollView Provides scrolling capability Content longer than screen height
RecyclerView Efficiently displays large datasets Lists, grids with dynamic data

View Attributes

Common XML attributes:

Attribute Description Example
android:id View identifier android:id="@+id/button1"
android:layout_width Width dimension android:layout_width="match_parent"
android:layout_height Height dimension android:layout_height="wrap_content"
android:text Display text android:text="@string/hello"
android:background Background color/resource android:background="@color/primary"
android:visibility Visibility state android:visibility="gone"

Adapters

Role: Bridge between data source and View components like ListView or RecyclerView.

Action Bar

Dialogs

Small windows that prompt user for decisions or additional information.

Dialog Type Description Use Case
AlertDialog Shows title, message, up to 3 buttons, list items, or custom layout Confirmations, alerts
DatePickerDialog Predefined UI for date selection Calendar events, scheduling
TimePickerDialog Predefined UI for time selection Alarm clocks, timers
ProgressDialog Shows progress bar Waiting for operations

Creating AlertDialog

AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Confirmation") .setMessage("Are you sure you want to delete?") .setPositiveButton("Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Handle positive button click } }) .setNegativeButton("Cancel", null) .show();

Notifications

Messages displayed outside regular app UI to inform users.

Component Description
Notification Icon Small icon shown in status bar
Notification Title Brief description
Notification Text Detailed information
Notification Drawer Area where user can view all notifications

Creating Notification

// Create notification channel (required for Android 8.0+) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( CHANNEL_ID, "Important Notifications", NotificationManager.IMPORTANCE_DEFAULT); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(channel); } // Build notification NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("New Message") .setContentText("You have a new message from John") .setPriority(NotificationCompat.PRIORITY_DEFAULT); // Show notification NotificationManagerCompat manager = NotificationManagerCompat.from(this); manager.notify(NOTIFICATION_ID, builder.build());

3. Data and App Interaction

3.1 Intents and Broadcasts

Intent: Message object describing an action to perform, including data and component that should handle it.
Broadcast: System-wide message sent to interested components.

Intent Types

Type Description Example
Explicit Intent Specifies exact component to start Intent intent = new Intent(this, TargetActivity.class);
Implicit Intent Describes action, system finds matching component Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"));

Starting Activities

// Explicit intent Intent explicitIntent = new Intent(this, TargetActivity.class); startActivity(explicitIntent); // Explicit intent with data Intent dataIntent = new Intent(this, TargetActivity.class); dataIntent.putExtra("key", "value"); startActivity(dataIntent); // Implicit intent (e.g., open URL) Intent implicitIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com")); startActivity(implicitIntent);

Broadcast Receivers

Components that respond to system-wide broadcasts.

3.2 Preferences and Saving

SharedPreferences Example

// Save preference SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); editor.putString("username", "john_doe"); editor.putInt("score", 100); editor.apply(); // Retrieve preference SharedPreferences prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE); String username = prefs.getString("username", "default"); int score = prefs.getInt("score", 0);

3.3 Content Providers and Services

Content Providers

Manage access to shared data between apps. Standardized interface for CRUD operations.

Services

Background components that perform long-running operations.

Creating a Service

public class MyService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { // Perform background work return START_STICKY; // Restart if killed } @Override public IBinder onBind(Intent intent) { return null; // Not a bound service } } // Start service Intent serviceIntent = new Intent(this, MyService.class); startService(serviceIntent);

3.4 AsyncTask and AsyncTaskLoader

Handles background operations and UI updates.

AsyncTask Lifecycle

private class MyTask extends AsyncTask { @Override protected void onPreExecute() { // UI setup before task } @Override protected Result doInBackground(Params... params) { // Background work return result; } @Override protected void onProgressUpdate(Progress... values) { // Update progress UI } @Override protected void onPostExecute(Result result) { // Update UI with result } }

4. Sensors and Communication

4.1 Sensors

Sensor Types

Sensor Type Description Example Use
Accelerometer Measures acceleration force Shaking gestures, tilt detection
Gyroscope Measures rotation Orientation tracking, gaming
Magnetometer Measures magnetic field Compass, magnetic detection
Light Measures ambient light Auto-brightness adjustment
Proximity Measures distance to object Phone call screen turns off
Temperature Measures ambient temperature Weather apps

Registering Sensor Listener

// Get SensorManager SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); // Get default sensor Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // Register listener sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL); // Implement callback @Override public void onSensorChanged(SensorEvent event) { float x = event.values[0]; float y = event.values[1]; float z = event.values[2]; // Handle sensor data } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Handle accuracy change }

4.2 Orientation and Movement

4.3 Sending and Receiving SMS

Requires SEND_SMS permission.

Sending SMS

// Check permission if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, REQUEST_SMS); } else { sendSMS("+1234567890", "Hello from my app!"); } private void sendSMS(String phoneNumber, String message) { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phoneNumber, null, message, null, null); }

5. Quick Reference Guide

Essential Files and Components

File/Component Purpose Key Methods/Attributes
AndroidManifest.xml App configuration and permissions <activity>, <service>, <uses-permission>
Activity User interface screen onCreate(), setContentView(), setTitle()
Fragment Reusable UI component onCreateView(), onAttach()
Service Background processing onStartCommand(), onBind()
BroadcastReceiver System event handler onReceive()
ContentProvider Data sharing between apps query(), insert(), update(), delete()
Layout XML User interface definition <LinearLayout>, <TextView>, android:layout_width

Common Layout Patterns

Pattern Layout Use Case
Single screen ConstraintLayout Standard app screens
List RecyclerView Scrollable lists with dynamic data
Form LinearLayout + EditText Data entry screens
Card-based RecyclerView with CardView items Gallery, product listings

Development Best Practices

6. Exam Preparation Tips

7. Summary and Key Takeaways

Android development requires understanding the platform architecture, user interface design, and app lifecycle management.

Essential components: Activities, Fragments, Services, BroadcastReceivers, and ContentProviders form the building blocks of Android apps.

UI development: Views and ViewGroups create the visual interface, with adapters handling data binding for lists and grids.

Data management: SharedPreferences, SQLite, ContentProviders, and Services handle data persistence and background processing.

System integration: Intents enable app-to-app communication and system feature access.

Sensor integration: Android's rich sensor framework enables innovative apps that respond to the physical world.

Best practices: Follow Android design guidelines, handle lifecycle properly, optimize performance, and test thoroughly.